package com.crayon2f.test;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.crayon2f.test.beans.Book;
import com.crayon2f.test.beans.User;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * Created by feifan.gou@gmail.com on 2020/8/26 15:50.
 */

public class TEST {

    @Test
    public void testStringIntern() {

        String s = new String("a");
        String s2 = new String("a");
        String s1 = "a";
        System.out.println(s.intern() == s1.intern());
        System.out.println(s1.intern() == s2.intern());
    }

    @Test
    public void testStringConstant() {

        String s1 = "1";
        String s2 = s1;
        s1 = "2";
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        System.out.println("".hashCode());


        User u = new User();
        User user = new User();
        user.setAge(3);
        User user1 = user;
        user = u;

        System.out.println(user.hashCode());
        System.out.println(user1.hashCode());


        Set<String> set = Sets.newHashSet();
        set.add("a");
        set.add("b");
        set.add("c");
        set.add("d");
        Set<String> set1 = Sets.newHashSet("b");
        System.out.println(set.containsAll(set1));
    }


    @Test
    public void test() {

        System.out.println((int) 'a');


    }

    @Test
    public void testRedission() {

//        RedissonLock redissonLock =
    }


    @Test
    public void testPattern() {

        Pattern pattern = Pattern.compile("[\\d]+");
        System.out.println(pattern.splitAsStream("aa3dd5dd6ll").collect(Collectors.joining(",")));
        System.out.println(pattern.asPredicate().test("345"));
    }

    @Test
    public void testCommonChars() {

        System.out.println(commonChars(new String[]{
                "bella", "label", "roller"
        }));
    }

    @Test
    public void testIsValid() {

        System.out.println(isValid("aabcbc"));
    }

    public List<String> commonChars(String[] A) {

        List<String> list = new LinkedList<>();
        Map<Integer, List<String>> map = new HashMap<>();
        for (int i = 0, aLength = A.length; i < aLength; i++) {
            String s = A[i];
            char[] chars = s.toCharArray();
            List<String> childList = new ArrayList<>();
            for (char aChar : chars) {
                childList.add(aChar + "");
            }
            map.put(i, childList);
        }
        List<String> strings = map.get(0);
        strings.forEach(s -> {
            boolean[] exist = {true};
            map.forEach((key, value) -> exist[0] = value.contains(s));
            if (exist[0]) {
                list.add(s);
            }
        });
        return list;
    }


    public boolean isValid(String s) {

        String SPLIT = "abc";
        if (Objects.isNull(s)) {
            return false;
        }
        if (!s.contains(SPLIT)) {
            return false;
        }
        s = s.replaceAll(SPLIT, "");
        if (s.isEmpty()) {
            return true;
        } else {
            while (s.contains(SPLIT)) {
                s = s.replace(SPLIT, "");
                if (s.isEmpty()) {
                    return true;
                }
                if (s.length() <= SPLIT.length()) {
                    return s.equals(SPLIT);
                }
            }
        }
//
//        String[] strings = s.split(SPLIT);
//        while (strings.length > 0) {
//            temp = String.join("", strings);
//            if (temp.length() <= SPLIT.length()) {
//                return temp.equals(SPLIT);
//            }
//            strings = temp.split(SPLIT);
//        }
        return false;
    }

    @Test
    public void testForEachContinue() {

        List<String> list = Lists.newArrayList(
                "1",
                "2",
                "3",
                "4",
                "5",
                "6"
        );
        System.out.println(t(list));
    }

    private String t(List<String> list) {

        list.forEach(s -> {
            if (s.equals("3")) {
                return;
            }
            System.out.println(s);
        });
        System.out.println("----------------------");
        Map<String, String> map = new HashMap<>();
        map.put("1", "2");
        map.put("s", "2");
        map.put("e", "2");
        map.put("1r", "2");
        map.forEach((key, value) -> {
            if (key.equals("e")) {
                return;
            }
            System.out.println(key);
        });
        return null;
    }

    public static void main(String[] args) {

        compareStr();
    }

    public static void compareStr() {

//        String s = new String("2");
        String s = "2";
//        s.intern();
        String s2 = "2";
        System.out.println(s == s2);

//        String s3 = new String("1") + new String("1");
        String s3 = "1" + "1";
//        s3.intern();
        String s4 = "11";
        System.out.println(s3 == s4);
    }

    @Test
    public void main() {

        compareStr();
    }


    @Test
    public void test2() {

        ArrayList<Integer> list = new ArrayList<>(5);
        for (int i = 0; i < 6; i++) {
            list.add(i);
        }
        list.trimToSize();
        System.out.println(list);
    }

    @Test
    public void test3() {

//        System.out.println(-7 >>> 1);
//
//        System.out.println(Integer.MAX_VALUE);

        List<String> noArgsList = new ArrayList<>();
//        noArgsList.add("22");
        List<String> argsList = new ArrayList<>(0);
        argsList.add("22");
        argsList.add("22");
        argsList.add("22");
        argsList.add("22");
        argsList.add("22");
        argsList.add("22");
        argsList.add("22");
        argsList.add("22");
        argsList.add("22");
        argsList.add("22");
        argsList.add("22");
        noArgsList.addAll(argsList);
        System.out.println(noArgsList);
        System.out.println(argsList);


    }

    static void bar() {

        System.out.println("bar");
    }

    @Test
    public void testTreeSet() {

        List<User> userList = new ArrayList<>();
        userList.add(new User("1", 1));
        userList.add(new User("1", 2));
        userList.add(new User("2", 4));
        userList.add(new User("2", 3));
        userList.add(new User("3", 6));
        userList.add(new User("3", 5));
//        ArrayList<User> collect = userList.stream()
//                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getAge))), ArrayList::new));
//
//        TreeSet<User> collect1 = userList.stream().collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getName))));
//
//        TreeSet<User> users = new TreeSet<>(Comparator.comparing(User::getName));
//        users.add(new User("1", 1));
//        users.add(new User("1", 12));
//        System.out.println(users);
//        System.out.println(collect);
//        System.out.println(collect1);

//        Map<String, List<User>> sortGroupMap = userList.stream()
//                .collect(Collectors.groupingBy(
//                        User::getName,
//                        Collectors.collectingAndThen(Collectors.toList(), list -> {
//                            list.sort(Comparator.comparing(User::getAge));
//                            return list;
//                        })
//                ));
//        System.out.println(sortGroupMap);

        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add(i);
        }
        System.out.println(list.stream().limit(21).collect(Collectors.toList()));

        System.out.println(Timestamp.valueOf(LocalDateTime.MAX).getTime());
    }

    @Test
    public void test0() {

//        System.out.println(bool1() || bool2() && bool3());

//        System.out.println(StringUtils.isNotEmpty(StringUtils.EMPTY) && StringUtils.EMPTY.matches("(\\d)+"));

        boolean bool = bool1();
        if (bool) {
            System.out.println("-----------------");
        }

        StringBuffer buffer = new StringBuffer("insert into test_table(a,b,c) values");
        for (int i = 0; i < 100000; i++) {
            String format = String.format("'%s'", UUID.randomUUID().toString().replaceAll("(-)", "").toUpperCase());
            buffer.append("(")
                    .append(format)
                    .append(",")
                    .append(format)
                    .append(",")
                    .append(format)
                    .append("),");
        }
        System.out.println(buffer.toString());

    }

    @Test
    @SneakyThrows
    public void test4() {


//        Runtime runtime = Runtime.getRuntime();
//        int freeMemory = (int) (runtime.freeMemory() / 1024 / 1024);
//        int totalMemory = (int) (runtime.totalMemory() / 1024 / 1024);
//        String result = freeMemory + "M/" + totalMemory + "M(free / total)";
//        System.out.println(result);

        Class<Book> clazz = Book.class;
        Field page = clazz.getDeclaredField("page");
        Field pageNumber = clazz.getDeclaredField("pageNumber");
        System.out.println(page.getType() == int.class);
        System.out.println(pageNumber.getType() == Integer.class);
        System.out.println("=============");
    }

    private boolean bool1() {

        if (bool3()) {
            throw new NullPointerException();
        }
        return false;
    }

    private boolean bool2() {

        return true;
    }

    private boolean bool3() {

        return true;
    }


    @Test
    public void testFor() {

        Long l = 1000L;
        Long l2 = 1000L;
        System.out.println(l == l2);
        Long l3 = 100L;
        Long l4 = 100L;
        System.out.println(l3 == l4);

    }

    @Test
    public void testJDK14() {

        List<Integer> of = Lists.newArrayList(1, 2, 3, 4, 5);
        Integer integer = of.stream().filter(ths -> {
            System.out.println(ths);
            return ths > 1;
        }).findFirst().orElse(6);
        int i = 6;
        for (Integer integer1 : of) {
            if (integer1 > 1) {
                i = integer1;
                break;
            }
        }
        System.out.println(i);

    }

    @SneakyThrows
    @Test
    public void test5() {

        @Cleanup
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        SXSSFSheet sheet = workbook.createSheet();
        { //培训标题
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            SXSSFRow row = sheet.createRow(0);
            Font font = workbook.createFont();
            font.setBold(true);
            font.setFontName("黑体");
            font.setFontHeightInPoints((short) 16);
            style.setFont(font);
            CellUtil.createCell(row, 0, "捍卫国家安全、反间谍知识培训20210415(一道考题）", style);
        }
        { //试卷标题
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            SXSSFRow row = sheet.createRow(1);
            Font font = workbook.createFont();
            font.setBold(true);
            font.setFontName("黑体");
            font.setFontHeightInPoints((short) 14);
            style.setFont(font);
            CellUtil.createCell(row, 0, "捍卫国家安全考题（满分：100；及格分：60）", style);
        }
        { //标题
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            SXSSFRow row = sheet.createRow(2);
            Font font = workbook.createFont();
            font.setBold(true);
            font.setFontName("黑体");
            font.setFontHeightInPoints((short) 12);
            style.setFont(font);
            CellUtil.createCell(row, 0, "应参加人数：1000 \r\n 实际参加人数：600 \r\n 参考人数：300", style);
        }
        CellRangeAddress address = new CellRangeAddress(0, 0, 0, 4);
        CellRangeAddress address1 = new CellRangeAddress(1, 1, 0, 4);
        CellRangeAddress address2 = new CellRangeAddress(2, 2, 0, 4);
        sheet.addMergedRegion(address);
        sheet.addMergedRegion(address1);
        sheet.addMergedRegion(address2);
        setSizeColumn(sheet);
        workbook.write(new FileOutputStream("C:\\Users\\goufeifan\\Desktop\\merge.xlsx"));
    }

    // 自适应宽度(中文支持)
    private void setSizeColumn(SXSSFSheet sheet) {
        for (int columnNum = 0; columnNum <= 8; columnNum++) {
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                SXSSFRow currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }

                if (currentRow.getCell(columnNum) != null) {
                    SXSSFCell currentCell = currentRow.getCell(columnNum);
                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            sheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    }

    @Test
    public void handleExcel() throws IOException, InvalidFormatException {

        XSSFWorkbook workbook = new XSSFWorkbook(new File("/Users/crayon2f/Downloads/data.xlsx"));
        XSSFSheet sheet = workbook.getSheet("Sheet3");
        boolean[] first = {false};
        Map<String, String> map = new HashMap<>();
        sheet.forEach(row -> {
            if (!first[0]) {
                first[0] = true;
                return;
            }
            map.put(String.format("%s(%s)", CellUtil.getCell(row, 0).getStringCellValue(), CellUtil.getCell(row, 1).getStringCellValue()), CellUtil.getCell(row, 5).getStringCellValue());
        });
        first[0] = false;
        sheet.forEach(row -> {
            if (!first[0]) {
                first[0] = true;
                return;
            }
            String leader = map.getOrDefault(CellUtil.getCell(row, 5).getStringCellValue(), "-");
            if (leader.startsWith("王韬")) {

            }
            row.createCell(6).setCellValue(leader);
            String leader2 = map.getOrDefault(leader, "-");
            row.createCell(7).setCellValue(leader2);
        });
        workbook.write(new FileOutputStream("/Users/crayon2f/Downloads/data2.xlsx"));
        workbook.close();
    }

    @Test
    @SneakyThrows
    public void main2() {

        List<Integer> collect = IntStream.rangeClosed(1, 100).boxed().collect(Collectors.toList());
        CollUtil.split(collect, 10).forEach(System.out::println);
        System.out.println("----------------------------------------");
        Lists.partition(collect, 10).forEach(System.out::println);

    }

}
